<?php

/**
 * member actions.
 *
 * @package    docplus.co.za
 * @subpackage member
 * @author     Fox Matuku
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class memberActions extends gfFrontendActions
{

    public function preExecute()
    {
        if ($this->getUser()->isAuthenticated())
        {
            if ($this->getUser()->getType() == "Member")
            {
                $this->memberId = $this->getUser()->getMember()->getId();
            }
        }
        parent::preExecute();
    }

    /**
     * Executes appointment action
     *
     * @param sfRequest $request A request object
     */
    public function executeAppointment(sfWebRequest $request)
    {
        
    }

    /**
     * Executes register action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegister(sfWebRequest $request)
    {
        $this->form = new MemberForm();
    }

    /**
     * Executes registerStepOne action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepOne(sfWebRequest $request)
    {
        $registrationDetails = $this->getUser()->getRegistrationDetails(array());
        $member = new Member();
        $member->setEmail(time() . '@' . 'docplus.co.za');

        $this->form = new MemberForm($member, array('is_step_one' => true));
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $registrationDetails = array();
                    $registrationDetails['first_name'] = $this->form->getValue('first_name');
                    $registrationDetails['last_name'] = $this->form->getValue('last_name');
                    $registrationDetails['profile_name'] = $this->form->getValue('profile_name');
                    $registrationDetails['gender'] = $this->form->getValue('gender');

                    // push the modified registration details to the user session
                    $this->getUser()->setRegistrationDetails($registrationDetails);

                    //proceed to step two
                    $this->redirect("@member_register_step_two");
                }
                catch (Exception $e)
                {
                    die($e);
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes registerStepTwo action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepTwo(sfWebRequest $request)
    {
        $registrationDetails = $this->getUser()->getRegistrationDetails(false);
        $this->forward404Unless($registrationDetails);

        $this->galleryItem = GalleryItemTable::getInstance()->findOneByIsDefault(1);
        $this->forward404Unless($this->galleryItem);

        $contact = new Contact();
        $contact->setUserId(time());
        $contact->setCityId(sfConfig::get("app_default_city"));
        $contact->setRegionId(sfConfig::get("app_default_region"));

        $member = new Member();
        $member->setFirstName($registrationDetails['first_name']);
        $member->setLastName($registrationDetails['last_name']);
        $member->setProfileName($registrationDetails['profile_name']);
        $member->setGender($registrationDetails['gender']);
        $member->setLanguageId(sfConfig::get("app_default_language"));

        $this->contactForm = new MemberContactForm($contact);
        $this->memberForm = new MemberForm($member, array('is_step_two' => true, 'gallery_item_id' => $this->galleryItem->getId()));

        if ($request->isMethod('post'))
        {
            $this->contactForm->bind($request->getParameter($this->contactForm->getName()));
            $this->memberForm->bind($request->getParameter($this->memberForm->getName()));

            if ($this->contactForm->isValid() && $this->memberForm->isValid())
            {
                try
                {
                    $member = $this->memberForm->save();

                    $contactValues = $request->getParameter($this->contactForm->getName());
                    $contactValues['user_id'] = $member->getUserId();
                    $this->contactForm->bind($contactValues);
                    $contact = $this->contactForm->save();

                    // set the mobile activation code
                    $contact->setMobileActivationCode(rand(10000, 99999));
                    $contact->save();

                    // activate the user
                    $user = $member->getUser();
                    $user->setIsActive(true);
                    $user->save();

                    // save the gallery item
                    $user->_saveUserGalleryItem();

                    // send the welcome email...
                    // seems everything has gone smoothly...so we can as well log them in :)
                    $this->getUser()->signin($user, $this);
                }
                catch (Exception $e)
                {
                    throw $e;
                }
                //proceed to step three
                $this->redirect("@member_register_step_three?command=stay");
            }
        }
    }

    /**
     * Executes registerStepThree action
     *
     * @param sfRequest $request A request object
     */
    public function executeRegisterStepThree(sfWebRequest $request)
    {        
        $this->user = $this->getUser()->getDpUser();
        $this->redirectUnless($this->user, "@home");

        $this->command = $request->getParameter("command", "stay");
        $this->galleryItem = GalleryItemTable::getInstance()->findOneByIsDefault(1);
        $this->forward404Unless($this->galleryItem);

        $this->form = new myProfilePhotoForm(array('gallery_item_id' => $this->galleryItem->getId()));

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                // save the gallery item
                $this->user->_saveUserGalleryItem($this->form->getValue('gallery_item_id'));

                $this->getUser()->setFlash('notice', 'Congratulations, you\'ve successfully signed up for an account on DocPlus!');

                //proceed to confirmation
                $this->redirect("@member_welcome");
            }
        }
    }

    /**
     * Executes publicProfile action
     *
     * @param sfRequest $request A request object
     */
    public function executePublicProfile(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("profile_public");

        $this->member = MemberTable::getInstance()->findOneByUserSlug($request['slug']);
        $this->user = $this->member->getUser();

        // fetch the question answer comment form
        $this->_getAnswerCommentForm();
    }

    /**
     * Executes profile action
     *
     * @param sfRequest $request A request object
     */
    public function executeProfile(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("member_profile");

        $this->user = $this->getUser()->getDpUser();
        $this->forward404Unless($this->user);
        $this->member = MemberTable::getInstance()->findOneByUserId($this->user->getId());

        $this->form = new myMemberForm($this->member);
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    // save member details
                    $member = $this->form->save();

                    // save the gallery item
                    $this->_saveUserGalleryItem($this->user, $this->form);

                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');
                    $this->redirect("@member_profile");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
            else
            {
//                foreach ($this->form as $field)
//                {
//                    echo $field->renderLabel() . " " . $field->renderError() . "<br />";
//                }
//                die($this->form->renderGlobalErrors());
            }
        }
    }

    /**
     * Executes contact details action
     *
     * @param sfRequest $request A request object
     */
    public function executeContactDetails(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("member_profile");

        $dpUser = $this->getUser()->getDpUser();
        $this->forward404Unless($dpUser);

        $this->form = new myContactForm($dpUser->getContact());
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $member = $this->form->save();
                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');

                    $this->redirect("@member_contact_details");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    /**
     * Executes credentials action
     *
     * @param sfRequest $request A request object
     */
    public function executeCredentials(sfWebRequest $request)
    {
        // set the current route
        $this->getUser()->setCurrentRoute("member_profile");

        $dpUser = $this->getUser()->getDpUser();
        $this->forward404Unless($dpUser);

        $this->form = new myCredentialsForm(array(
                "user_id" => $dpUser->getId(),
                "email" => $dpUser->getEmail()),
                array("user" => $dpUser)
        );

        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid())
            {
                try
                {
                    $member = $this->form->save();
                    $this->getUser()->setFlash('notice', 'The item was updated successfully.');

                    $this->redirect("@member_credentials");
                }
                catch (Exception $e)
                {
                    // invoke the event here so we get the error via email
                }
            }
        }
    }

    public function executeQuestions(sfWebRequest $request)
    {
        $this->getUser()->setCurrentRoute("member_questions");

        $user = GfUserTable::getInstance()->findOneBySlug($request['slug']);
        $this->questions = QuestionTable::getInstance()->retrieveByUserId($user->getId());

        // fetch the answer comment form
        $this->_getAnswerCommentForm();
    }

    /**
     * Executes welcome action
     *
     * @param sfRequest $request A request object
     */
    public function executeWelcome(sfWebRequest $request)
    {
    }
}
